import { UiButton } from '@/shared/Uikit'
import { useEffect, useState } from 'react'
import { useGetQuestions } from '../model/useGetQuestions'

type TestBlockProps = {
    testId: number
}

const TestBlock = (props: TestBlockProps) => {
    const [results, setResults] = useState<{ question: string; answer: string | undefined }[]>([])
    const { questions, isSuccess } = useGetQuestions(props.testId)

    const localStorageKey = `testResults_${props.testId}`

    useEffect(() => {
        if (questions && isSuccess) {
            const newResults = questions.map(question => ({
                question: question.question,
                answer: undefined
            }));
            setResults(newResults);
        }
    }, [questions]);

    useEffect(() => {
        const storedResults = localStorage.getItem(localStorageKey)
        if (storedResults) {
            try {
                setResults(JSON.parse(storedResults))
            } catch (error) {
                console.error('Error parsing stored results:', error)
            }
        }
    }, [props.testId])


    const handleSaveResults = (results: { question: string; answer: string | undefined }[]) => {
        localStorage.setItem(localStorageKey, JSON.stringify(results))
    }

    const handleAnswerClick = (questionIndex: number, answer: string) => {
        setResults(prevResults => {
            const updatedResults = [...prevResults]
            updatedResults[questionIndex] = {
                question: prevResults[questionIndex].question,
                answer: answer
            }
            handleSaveResults(updatedResults)
            return updatedResults
        })
    }

    return (
        <div>
            {isSuccess && !!questions?.length && (
                <div className='w-full flex justify-center px-24'>
                    <div>
                        {questions.map((question, questionIndex) => (
                            <div key={question.question} className="m-4 max-w-[500px] rounded-md p-4 min-w-[250px]">
                                <h1 className="text-[20px] font-bold">Вопрос: {question.question}</h1>
                                <ul>
                                    {question.choices.map((answer, index) => (
                                        <li
                                            key={answer}
                                            className={
                                                results[questionIndex]?.answer === answer
                                                    ? "cursor-pointer mt-4 p-3 border rounded-md bg-gray-300"
                                                    : "cursor-pointer mt-4 p-3 border rounded-md"
                                            }
                                            onClick={() => handleAnswerClick(questionIndex, answer)}
                                        >
                                            {answer}
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    )
}

export default TestBlock